<template>
  <div class="route-list">
    <el-card>
      <!-- 搜索和添加按钮 -->
      <div class="header">
        <el-input
          v-model="searchText"
          placeholder="请输入配送员"
          style="width: 300px; margin-right: 10px"
          clearable
          @keyup.enter="fetchDeliveryList"
        />
        <el-select 
          v-model="searchStatus" 
          placeholder="配送状态" 
          clearable 
          style="width: 150px; margin-right: 10px"
        >
          <el-option label="取货中" value="1" />
          <el-option label="配送中" value="2" />
          <el-option label="已完成" value="3" />
        </el-select>
        <el-button type="primary" @click="fetchDeliveryList">搜索</el-button>
        <el-button type="success" @click="handleAdd">新增派送</el-button>
      </div>

      <!-- 派送表格 -->
      <el-table :data="deliveryList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userName" label="配送员" width="120" />
        <el-table-column prop="address" label="配送地址" min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建人" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" link @click="handleViewProcess(scope.row)">查看明细</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchDeliveryList"
        @current-change="fetchDeliveryList"
        style="margin-top: 20px"
      />
    </el-card>

    <!-- 添加/编辑派送对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增派送' : '编辑派送'"
      width="500px"
      @close="resetForm"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="配送员" prop="userName">
          <el-input v-model="form.userName" />
        </el-form-item>
        <el-form-item label="配送地址" prop="address">
          <el-input type="textarea" v-model="form.address" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="取货中" value="1" />
            <el-option label="配送中" value="2" />
            <el-option label="已完成" value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 派送明细对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="派送明细"
      width="800px"
    >
      <el-table :data="processList" style="width: 100%" border>
        <el-table-column prop="freshFoodId" label="生鲜ID" width="100" />
        <el-table-column prop="freshFoodName" label="生鲜名称" width="150" />
        <el-table-column prop="price" label="价格" width="100" />
        <el-table-column prop="number" label="数量" width="100" />
        <el-table-column prop="isPromotion" label="是否促销" width="100">
          <template #default="scope">
            {{ scope.row.isPromotion === '1' ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { get, post } from '@/api/api'

// 列表数据
const deliveryList = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchText = ref('')
const searchStatus = ref('')

// 对话框数据
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref()
const form = ref({
  id: null,
  userId: '',
  userName: '',
  address: '',
  status: ''
})

// 派送过程对话框
const processDialogVisible = ref(false)
const processList = ref([])

// 派送过程相关数据
const processFormDialogVisible = ref(false)
const processFormRef = ref()
const processForm = ref({
  deliveryId: null,
  freshFoodId: null,
  freshFoodName: '',
  price: 0,
  number: 1,
  isPromotion: '0'
})

// 表单校验规则
const rules = {
  userName: [{ required: true, message: '请输入配送员', trigger: 'blur' }],
  address: [{ required: true, message: '请输入配送地址', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 派送过程表单校验规则
const processRules = {
  freshFoodId: [{ required: true, message: '请输入生鲜ID', trigger: 'blur' }],
  freshFoodName: [{ required: true, message: '请输入生鲜名称', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  number: [{ required: true, message: '请输入数量', trigger: 'blur' }]
}

// 获取派送列表
const fetchDeliveryList = async () => {
  try {
    const res = await get('/delivery/page', {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      userId: searchText.value,
      status: searchStatus.value
    })
    if (res && res.data) {
      deliveryList.value = res.data.records
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取派送列表失败:', error)
    ElMessage.error('获取派送列表失败')
  }
}

// 查看派送过程
const handleViewProcess = async (row) => {
  try {
    const res = await get(`/delivery/process/${row.id}`)
    if (res && res.data) {
      processList.value = res.data
      processDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取派送过程失败:', error)
    ElMessage.error('获取派送过程失败')
  }
}

// 打开添加对话框
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetForm()
}

// 打开编辑对话框
const handleEdit = async (row) => {
  try {
    const res = await get(`/delivery/detail/${row.id}`)
    if (res && res.data) {
      dialogType.value = 'edit'
      form.value = { ...res.data }
      dialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error('获取派送详情失败')
  }
}

// 删除派送
const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该派送记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await post('/delivery/remove', { id: row.id })
      ElMessage.success('删除成功')
      fetchDeliveryList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = dialogType.value === 'add' ? '/delivery/save' : '/delivery/update'
        await post(url, form.value)
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
        fetchDeliveryList()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  form.value = {
    id: null,
    userName: '',
    address: '',
    status: '1'
  }
}

// 状态转换
const getStatusText = (status) => {
  const statusMap = {
    '1': '取货中',
    '2': '配送中',
    '3': '已完成'
  }
  return statusMap[status] || '未知'
}

const getStatusType = (status) => {
  const typeMap = {
    '1': 'warning',
    '2': 'primary',
    '3': 'success'
  }
  return typeMap[status] || 'info'
}

// 添加派送过程
const handleAddProcess = (deliveryId) => {
  processForm.value.deliveryId = deliveryId
  processFormDialogVisible.value = true
}

// 提交派送过程表单
const handleProcessSubmit = async () => {
  await processFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await post('/delivery/process/save', processForm.value)
        ElMessage.success('添加成功')
        processFormDialogVisible.value = false
        // 刷新派送过程列表
        if (processForm.value.deliveryId) {
          handleViewProcess({ id: processForm.value.deliveryId })
        }
      } catch (error) {
        ElMessage.error('添加失败')
      }
    }
  })
}

// 重置派送过程表单
const resetProcessForm = () => {
  if (processFormRef.value) {
    processFormRef.value.resetFields()
  }
  processForm.value = {
    deliveryId: null,
    freshFoodId: null,
    freshFoodName: '',
    price: 0,
    number: 1,
    isPromotion: '0'
  }
}

// 初始化
onMounted(() => {
  fetchDeliveryList()
})
</script>

<style scoped>
.route-list {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
</style> 